﻿using Microsoft.AspNetCore.Mvc;
using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Core.Utils;
using PMS.Core.Utils.Authentication;
using PMS.Data.Entities.Settings;
using PMS.Services.EntityServices.Medias;
using PMS.Web.Framework.Mvc.Filters;
using System;

namespace PMS.Web.Framework.Controllers
{
    [AutoValidateAntiforgeryToken]
    [ValidateIpAddress]
    [AuthorizeCustomer(CustomerAuthorizeType.Admin)]
    public abstract partial class BaseAdminController : BaseController
    {
        private const int MAX_MEDIAFILE_UPLOAD = 20;
        #region Utils
        protected string EncodeId(int Id)
        {
            if (Id <= 0) return string.Empty;
            return HashidsHelper.Encode(AuthenticationDefaultConfigs.ItemIdHashSalt, Id);
        }

        protected int DecodeId(string hashId)
        {
            if (string.IsNullOrEmpty(hashId)) return 0;
            return HashidsHelper.Decode(AuthenticationDefaultConfigs.ItemIdHashSalt, hashId);
        }

        /// <summary>
        /// 通用设置文件上传各参数，便于页面中设置上传媒体文件各基础参数
        /// </summary>
        /// <param name="mediaSettings"></param>
        /// <param name="fileType">限制上传文件类型</param>
        /// <param name="max">限制上传文件数量</param>
        /// <returns></returns>
        protected void GetMediaFileUploadLimitations(MediaSettings mediaSettings, MediaFileType fileType = MediaFileType.Image, int max = int.MaxValue, MediaFileUseage useage = MediaFileUseage.Article)
        {
            //按类型指定文件上传最大允许文件容量
            ViewBag.MaxUploadSize = fileType switch
            {
                MediaFileType.Audio => mediaSettings.AudioMaximumSizeBytes,
                MediaFileType.Image => mediaSettings.ImageMaximumSizeBytes,
                MediaFileType.TextFile => mediaSettings.TxtFileMaximumSizeBytes,
                MediaFileType.Video => mediaSettings.VideoMaximumSizeBytes,
                MediaFileType.ZipFile => mediaSettings.ZipFileMaximumSizeBytes,
                _ => 3145728 //未指定上传文件类型时，设定统一上传文件大小为最小值 3M
            };
            //指定单次允许上传文件数量
            ViewBag.MaxUploadCount = Math.Min(max, MAX_MEDIAFILE_UPLOAD);
            //指定允许上传文件类型，即文件扩展名
            ViewBag.UploadExtNames = fileType == MediaFileType.Unknown
               ? "*"
               : string.Join(',', MimeTypesManager.Instance.GetSupportFileExtensionsByCategory(fileType)); 
            //指定上传文件的分类描述
            ViewBag.Useage = Enum.ToObject(typeof(MediaFileUseage), useage).ToString();
        }
        #endregion
    }
}
